package com.sinosoft.brokerchannel.base.utile;

import com.sinosoft.brokerchannel.base.common.ChannelConstants;
import org.apache.commons.codec.Charsets;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;

/**
 * 加解密工具类
 */
public class AESUtil {
    /**
     * logger，日志打印
     */
    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);
    /**
     * 字符编码："UTF-8"
     */
    private static final String defaultCharset = "UTF-8";
    /**
     * 加密秘钥：“AEC”
     */
    private static final String KEY_AES = "AES";
    /**
     * 请求算法名称：MD5
     */
    private static final String KEY_MD5 = "MD5";
    /**
     * 提供信息摘要算法的功能
     */
   
    /**
     * 加密
     *
     * @param data 需要加密的内容
     * @param key  加密密钥
     * @return 加密后内容
     */
    public static String encrypt(String data, String key) throws BusinessException {
        return doAES(data, key, Cipher.ENCRYPT_MODE);
    }

    /**
     * 解密
     *
     * @param data 待解密内容
     * @param key  解密密钥
     * @return 解密后内容
     */
    public static String decrypt(String data, String key) throws BusinessException {
        return doAES(data, key, Cipher.DECRYPT_MODE);
//        return data;
    }

    /**
     * @param data 要加密的内容
     * @param key  加密秘钥
     * @param mode 选择加解密的模式：2为ENCRYPT_MODE加密，1为 ENCRYPT_MODE 解密
     * @return 加密内容
     * 方法描述：选择是否加密，mode为2加密处理，其他则不加密
     */
    private static String doAES(String data, String key, int mode) throws BusinessException {
        try {
            // 初始化
        	MessageDigest md5Digest = MessageDigest.getInstance(KEY_MD5);
        	Cipher cipher = Cipher.getInstance(KEY_AES);
            cipher.init(mode, new SecretKeySpec(md5Digest.digest(key.getBytes(defaultCharset)), KEY_AES));
            if (mode == Cipher.ENCRYPT_MODE) {
                return new String(Base64.encodeBase64(cipher.doFinal(data.getBytes(defaultCharset)), false), Charsets.toCharset(defaultCharset));
            } else {
                return new String(cipher.doFinal(Base64.decodeBase64(data.getBytes())), Charsets.toCharset(defaultCharset));
            }
        } catch (Exception e) {
            logger.error("AES密文处理异常", e);
            throw new BusinessException(ChannelConstants.ExceptionResult.AESERROR.getCode(),
                    ChannelConstants.ExceptionResult.AESERROR.getMessage());
        }
    }
}
